package net.wanho.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import net.wanho.shop.dto.GoodsDTO;
import net.wanho.shop.dto.GoodsPicsAttrsDTO;
import net.wanho.shop.mapper.GoodsAttrMapper;
import net.wanho.shop.mapper.GoodsMapper;
import net.wanho.shop.mapper.GoodsPicsMapper;
import net.wanho.shop.po.Goods;
import net.wanho.shop.po.GoodsAttr;
import net.wanho.shop.po.GoodsPics;
import net.wanho.shop.service.GoodsService;
import net.wanho.shop.vo.GoodsOneVO;
import net.wanho.shop.vo.GoodsVo;
import net.wanho.shop.vo.PageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 猛虎王
 * @since 2024-12-24
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class GoodsServiceImpl implements GoodsService {

    private final GoodsMapper goodsMapper;
    private final GoodsPicsMapper goodsPicsMapper;
    private final GoodsAttrMapper goodsAttrMapper;

    /**
     * 商品表分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param goods
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo findPage(int pageNum, int pageSize, Goods goods) {
        if (ObjectUtil.isNull(goods)) {
            goods = new Goods();
        }

        // 分页
        PageHelper.startPage(pageNum, pageSize);
        List<Goods> goodsList = goodsMapper.select(goods);
        return new PageInfo(goodsList);
    }

    /**
     * 根据主键查询商品表
     *
     * @param goodsId
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public GoodsOneVO findById(Integer goodsId) {
        return goodsMapper.selectById(goodsId);
    }

    /**
     * 商品表新增
     *
     * @param goods
     */
    @Override
    public void add(Goods goods) {
        goodsMapper.insert(goods);
    }

    /**
     * 修改商品表
     *
     * @param
     */
    @Override
    public void modify(GoodsDTO goodsDTO) {
        /**
         * 1.修改商品信息
         */
        //  将GoodsDTO转换为Goods
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsDTO, goods);
        // 将商品分类字符串转换为商品分类id
        List<Integer> catIds = Arrays.stream(goodsDTO.getGoodsCat().split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        goods.setCatOneId(catIds.get(0));
        goods.setCatTwoId(catIds.get(1));
        goods.setCatThreeId(catIds.get(2));
        goods.setCatId(catIds.get(2));
        goods.setUpdateTime(LocalDateTime.now());
        goodsMapper.update(goods);

        /**
         * 2.修改商品图片
         */
        // 去除被删除的图片
        List<Integer> picsIds = new ArrayList<>(); // 获取保留的图片id
        goodsDTO.getPics().forEach(goodsPics -> {
            if (!ObjectUtil.isEmpty(goodsPics.getPicsId())) {
                picsIds.add(goodsPics.getPicsId());
            }
        });

        goodsPicsMapper.deleteBatchIds(goods.getGoodsId(), picsIds); // 根据商品id，删除不在保留图片id中的图片

        // 新增图片
        goodsDTO.getPics().forEach(goodsPics -> {
            if (ObjectUtils.isEmpty(goodsPics.getPicsId())) {
                goodsPics.setGoodsId(goods.getGoodsId());
                goodsPics.setPicsMid(goodsPics.getPicsBig());
                goodsPics.setPicsSma(goodsPics.getPicsBig());
                goodsPicsMapper.insert(goodsPics);
            }
        });

        /**
         * 3.商品参数，删除原来的参数，然后重新插入参数
         */
        goodsAttrMapper.deleteByGoodsId(goods.getGoodsId());
        goodsDTO.getAttrs().forEach(goodsAttr -> {
            goodsAttr.setGoodsId(goods.getGoodsId());
            goodsAttrMapper.insert(goodsAttr);
        });

    }

    /**
     * 根据主键删除商品表
     *
     * @param goodsId
     */
    @Override
    public void removeById(Serializable goodsId) {
        if (((String) goodsId).contains(",")) {
            goodsMapper.deleteByIds(((String) goodsId).split(","));
        } else {
            goodsMapper.deleteById(goodsId);
        }


    }

    @Override
    public PageVo find(Integer pageNum, Integer pageSize, GoodsDTO goodsDTO) {
        PageHelper.startPage(pageNum, pageSize);

        List<GoodsVo> goods = goodsMapper.find(goodsDTO);
        PageInfo<GoodsVo> pageInfo = new PageInfo<>(goods);

        List<GoodsVo> list = pageInfo.getList();
        list.forEach(System.out::println);

        PageVo pageVo = new PageVo(pageInfo.getTotal(), pageInfo.getPages());
        pageVo.put("goods", pageInfo.getList());
        return pageVo;
    }

    @Override
    public void addGoods(GoodsPicsAttrsDTO goodsPicsAttrsDTO) {

        Goods goods = getGoods(goodsPicsAttrsDTO);
        // 添加商品
        goodsMapper.insert(goods);

        List<GoodsPics> pics = goodsPicsAttrsDTO.getPics();
        List<GoodsAttr> attrs = goodsPicsAttrsDTO.getAttrs();

        Integer goodsId = goods.getGoodsId();
        // 添加图片
        goodsPicsAttrsDTO.getPics().forEach(goodsPics -> {
            goodsPics.setGoodsId(goodsId);
            goodsPics.setPicsBig(goodsPics.getPicsBig());
            goodsPics.setPicsMid(goodsPics.getPicsBig());
            goodsPics.setPicsSma(goodsPics.getPicsBig());
            goodsPicsMapper.insert(goodsPics);
        });

        // 添加参数
        goodsPicsAttrsDTO.getAttrs().forEach(goodsAttr -> {
            goodsAttr.setGoodsId(goodsId);
            goodsAttrMapper.insert(goodsAttr);
        });


    }

    @Override
    public void updateByIdState(Integer goodsId, Integer goodsState) {
        goodsMapper.updateById(goodsId, goodsState);
    }

    private Goods getGoods(GoodsPicsAttrsDTO goodsPicsAttrsDTO) {
        Goods goods = new Goods();
        goods.setGoodsName(goodsPicsAttrsDTO.getGoodsName());
        goods.setGoodsPrice(goodsPicsAttrsDTO.getGoodsPrice());
        goods.setGoodsNumber(goodsPicsAttrsDTO.getGoodsNumber());
        goods.setGoodsIntroduce(goodsPicsAttrsDTO.getGoodsIntroduce());
        goods.setGoodsWeight(goodsPicsAttrsDTO.getGoodsWeight());
        // 商品分类
        String[] split = goodsPicsAttrsDTO.getGoodsCat().split(",");
        goods.setCatOneId(Integer.parseInt(split[0]));
        goods.setCatTwoId(Integer.parseInt(split[1]));
        goods.setCatThreeId(Integer.parseInt(split[2]));
        // 添加时间
        goods.setCreateTime(LocalDateTime.now());
        // 修改时间
        goods.setUpdateTime(LocalDateTime.now());
        return goods;
    }


}
